<?php

namespace app\times\controller\oprate;

use think\Db;
use think\Log;

/**
 * 费改
 * Class
 * @package
 */
class Feemods
{

	/**
	 * 实例对象
	 * @var object
	 */
	protected static $instance;

	/**
	 * 默认配置
	 * @var array
	 */
	protected $config  = [
		"rate" 		=> "equip_rate",
		"apply" 	=> "equip_rate_mods_apply",
		"times"		=> "equip_rate_mods_times"
	];

	/**
	 * 实例化
	 */
	public static function instance()
	{
		if (is_null(self::$instance)) {
			self::$instance = new static();
		}
		return self::$instance;
	}

	/**
	 * 修改 - 操作
	 */
	public function handle($id)
	{
		if (!empty($id)) {
			$rateUp = [];
			$info = $this->gets($id);
			if ($info["is_apply"] == 1 && $info["status"] == 1) {
				$rateUp = [
					"proid" => $info['pro_id'],
					"sn" => $info['sn'],
					"state" => $info["apply_typs"],
					"sort" => $info["nums"]
				];
				$checkRate = Db::name($this->config["rate"])->where($rateUp)->count();
				if ($checkRate) {
					$up = ["rate" => $info['appy_rate'], "isModfy" => 1, "modify_time" => time()];
					if ($info['apply_typs'] == 'T') {
						$up["sort"] = $info['nums'];
						$up["differ"] = bcsub((string)$info['appy_rate'], (string)$info['orig_rate'], 2);
					}
					$ret = Db::name($this->config["rate"])->where($rateUp)->update($up);
					if ($ret) {
						return true;
					}
				} else {
					$rateUp["rate"] = $info['appy_rate'];
					$rateUp["isModfy"] = 1;
					$rateUp["modify_time"] = time();
					if ($info['apply_typs'] == 'T') {
						$rateUp["sort"] = $info['nums'];
						$rateUp["differ"] = bcsub((string)$info['appy_rate'], (string)$info['orig_rate'], 2);
					}
					$ret = Db::name($this->config["rate"])->insert($rateUp);
					if ($ret) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * @return boolean
	 */
	public function del_times_cords($id = "")
	{
		return Db::name($this->config["times"])->where("id = " . $id)->delete();
	}

	/**
	 * @return array|boolean
	 */
	public function gets($id = "")
	{
		if (!empty($id)) {
			$find = Db::name($this->config["apply"])->where("id=" . $id)->find();
			if ($find) {
				return $find;
			}
		}
		return false;
	}
}
